package com.example.springboot.controller;

import com.example.springboot.dto.*;
import com.example.springboot.service.MerchantService;
import com.example.springboot.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("api/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    /**
     * 根据经纬度获取附近的商家和自助点
     */
    @GetMapping("/nearby")
    public Map<String, Object> getNearbyData(@RequestParam double latitude, @RequestParam double longitude) {
        Map<String, Object> response = new HashMap<>();
        List<MerchantDTO> merchants = merchantService.getMerchantsByDistance(latitude, longitude);
        List<SelfServicePointDTO> selfServicePoints = merchantService.getSelfServicePointsByDistance(latitude, longitude);
        response.put("merchants", merchants);
        response.put("selfServicePoints", selfServicePoints);
        return response;
    }  /**
     * 根据商家ID获取商家详情
     */
    @GetMapping("/detail/{merchantId}")
    public Map<String, Object> getMerchantDetail(@PathVariable("merchantId") int merchantId,
                                                 @RequestParam double latitude,
                                                 @RequestParam double longitude) {
        Map<String, Object> response = new HashMap<>();
        MerchantDTO merchant = merchantService.getMerchantById(merchantId);

        if (merchant != null) {
            // 手动计算距离并设置
            double distance = merchantService.calculateDistance(latitude, longitude, merchant.getLatitude(), merchant.getLongitude());
            merchant.setDistance(distance);
            response.put("merchant", merchant);
        } else {
            response.put("error", "商家未找到");
        }

        return response;
    }
    /**
     * 根据自助点ID获取自助点详情
     */
    @GetMapping("/self-service-point/detail/{pointId}")
    public Map<String, Object> getSelfServicePointDetail(@PathVariable("pointId") int pointId,
                                                         @RequestParam double latitude,
                                                         @RequestParam double longitude) {
        Map<String, Object> response = new HashMap<>();
        SelfServicePointDTO point = merchantService.getSelfServicePointById(pointId);

        if (point != null) {
            // 手动计算距离并设置
            double distance = merchantService.calculateDistance(latitude, longitude, point.getLatitude(), point.getLongitude());
            point.setDistance(distance);
            response.put("point", point);
        } else {
            response.put("error", "自助点未找到");
        }

        return response;
    }

    /**
     * 根据商家ID获取服务类型
     */
    @GetMapping("/services/{merchantId}")
    public Map<String, Object> getMerchantServices(@PathVariable("merchantId") int merchantId) {
        Map<String, Object> response = new HashMap<>();
        String services = merchantService.getServicesByMerchantId(merchantId);

        if (services != null) {
            response.put("services", services);
        } else {
            response.put("error", "商家未找到或无服务信息");
        }
        return response;
    }

    /**
     * 根据商家ID获取商家订单列表
     */
    @GetMapping("/orders/{merchantId}")
    public Map<String, Object> getMerchantOrders(@PathVariable("merchantId") int merchantId) {
        Map<String, Object> response = new HashMap<>();
        List<MerchantOrderDTO> orders = merchantService.getOrdersByMerchantId(merchantId);

        if (!orders.isEmpty()) {
            response.put("orders", orders);
            response.put("totalOrders", orders.size());
            response.put("totalAmount", orders.stream()
                    .mapToDouble(order -> order.getOrderAmount().doubleValue()) // 假设 getOrderAmount 返回 BigDecimal
                    .sum());
        } else {
            response.put("message", "无订单记录");
        }

        return response;
    }
    @Autowired
    private OSSService ossService;
    /**
     * 修改商家头像
     */
    @PostMapping("/update-avatar/{merchantId}")
    public ResponseEntity<Map<String, Object>> updateMerchantAvatar(
            @PathVariable("merchantId") int merchantId,
            @RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("上传文件不能为空");
            }
            String avatarUrl = ossService.uploadImage(file);
            merchantService.updateMerchantAvatar(merchantId, avatarUrl);

            response.put("success", true);
            response.put("avatarUrl", avatarUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改商家海报
     */
    @PostMapping("/update-poster/{merchantId}")
    public ResponseEntity<Map<String, Object>> updateMerchantPoster(
            @PathVariable("merchantId") int merchantId,
            @RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("上传文件不能为空");
            }
            String posterUrl = ossService.uploadImage(file);
            merchantService.updateMerchantPoster(merchantId, posterUrl);

            response.put("success", true);
            response.put("posterUrl", posterUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    @GetMapping("/{merchantId}")
    public MerchantUsernameImageDTO getMerchantById(@PathVariable Integer merchantId) {
        return merchantService.getMerchantById(merchantId);
    }
    /**
     * 新增商家
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addMerchant(@RequestPart("merchantManagementDTO") MerchantManagementDTO merchantManagementDTO,
                                                           @RequestPart(value = "avatar", required = false) MultipartFile avatar,
                                                           @RequestPart(value = "poster", required = false) MultipartFile poster) throws Exception {
        // 上传图片到OSS并获取URL
        if (avatar != null) {
            String avatarUrl = ossService.uploadImage(avatar);
            merchantManagementDTO.setAvatarUrl(avatarUrl);
        }
        if (poster != null) {
            String posterUrl = ossService.uploadImage(poster);
            merchantManagementDTO.setPoster(posterUrl);
        }

        Map<String, Object> response = merchantService.addMerchant(merchantManagementDTO);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新商家信息
     */
    @PutMapping("/update/{merchantId}")
    public ResponseEntity<Map<String, Object>> updateMerchant(@PathVariable("merchantId") int merchantId,
                                                              @RequestPart("merchantManagementDTO") MerchantManagementDTO merchantManagementDTO,
                                                              @RequestPart(value = "avatar", required = false) MultipartFile avatar,
                                                              @RequestPart(value = "poster", required = false) MultipartFile poster) throws Exception {
        // 上传图片到OSS并获取URL
        if (avatar != null) {
            String avatarUrl = ossService.uploadImage(avatar);
            merchantManagementDTO.setAvatarUrl(avatarUrl);
        }
        if (poster != null) {
            String posterUrl = ossService.uploadImage(poster);
            merchantManagementDTO.setPoster(posterUrl);
        }

        Map<String, Object> response = merchantService.updateMerchant(merchantId, merchantManagementDTO);
        return ResponseEntity.ok(response);
    }

    /**
     * 删除商家
     */
    @DeleteMapping("/delete/{merchantId}")
    public ResponseEntity<Map<String, Object>> deleteMerchant(@PathVariable("merchantId") int merchantId) {
        Map<String, Object> response = merchantService.deleteMerchant(merchantId);
        return ResponseEntity.ok(response);
    }


    /**
     * 根据商家 ID 修改商家名称
     */
    @PutMapping("/update-name/{merchantId}")
    public Map<String, Object> updateMerchantName(@PathVariable("merchantId") int merchantId, @RequestParam String name) {
        Map<String, Object> response = new HashMap<>();
        boolean success = merchantService.updateMerchantName(merchantId, name);
        response.put("success", success);
        return response;
    }

    @PutMapping("/update-services/{merchantId}")
    public Map<String, Object> updateMerchantServices(@PathVariable("merchantId") int merchantId,
                                                      @RequestParam("services") String services) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = merchantService.updateMerchantServices(merchantId, services);
            response.put("success", success);
            if (!success) {
                response.put("message", "更新失败，可能是商家ID不存在或数据未修改");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新过程中发生错误：" + e.getMessage());
        }
        return response;
    }

    /**
     * 获取所有商家（仅超级管理员）
     */
    @GetMapping("/all")
    public ResponseEntity<List<MerchantDTO>> getAllMerchants() {
        List<MerchantDTO> merchants = merchantService.getAllMerchants();
        return ResponseEntity.ok(merchants);
    }


    @GetMapping("/by-admin")
    public ResponseEntity<List<SelfServicePointNameDTO>> getSelfServicePointsByAdmin(@RequestParam("adminId") Integer adminId) {
        List<SelfServicePointNameDTO> points = merchantService.findByAdminId(adminId);
        return ResponseEntity.ok(points);
    }
    /**
     * 根据管理员ID获取商家列表（普通管理员）
     */
    @GetMapping("/by-admin/{adminId}")
    public ResponseEntity<List<MerchantDTO>> getMerchantsByAdmin(@PathVariable("adminId") Integer adminId) {
        List<MerchantDTO> merchants = merchantService.getMerchantsByAdminId(adminId);
        return ResponseEntity.ok(merchants);
    }
    /**
     * 根据订单ID获取商家订单详情
     */
    @GetMapping("/order/detail/{orderId}")
    public ResponseEntity<Map<String, Object>> getOrderDetail(@PathVariable("orderId") int orderId) {
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> orderDetail = merchantService.getOrderDetailById(orderId);

        if (orderDetail != null) {
            response.put("orderDetail", orderDetail);
            return ResponseEntity.ok(response);
        } else {
            response.put("error", "订单未找到");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

}
// Below is the code of /springboot/src/main/java/com/example/springboot/config/MybatisConfig.java